#include "command.h"

int _mkdir(char *argv[])
{
	/* check the number of cmd-line parameters is correct */
	int argc = 0;
	for (char **ptr = argv; *ptr != NULL; ptr++)
		argc++;

	if (argc < 2) {
		fprintf(stderr, "Usage: mkdir [-p] dir1, dir2, ...\n");
		return -1;
	}

	/* parse the cmd-line parameters */
	const char *optfmt = "p";
	int opt;
	int catch_opt_p = 0;
	while ((opt = getopt(argc, argv, optfmt)) != -1) {
		switch (opt) {
			case 'p':
				catch_opt_p = 1;
				break;
			default:
				fprintf(stderr, "Usage: mkdir [-p] dir1, dir2, ...\n");
				break;
		}
	}

	/* create the directory */
	const char *dir_name;
	mode_t mode = 0755; // the authority for directory
	if (!argv[optind]) {
		fprintf(stderr, "Usage: mkdir [-p] dir1, dir2, ...\n");
		return -1;
	}
	for (int i = optind; i < argc; i++) {
		dir_name = argv[i];

		if (catch_opt_p == 1) {
			char *tmp = strdup(dir_name);
			if (!tmp) {
				fprintf(stderr, "mkdir error: strdup\n");
				free(tmp);
				return -1;
			}

			char *p = tmp; // use pointer to check every part of the path
			if (*p == '/') // handle the absolute path
				p++;
			for (; *p != '\0'; p++) {
				if (*p == '/') {
					*p = '\0';
					// check if this part directory is exist
					struct stat st;
					if (stat(tmp, &st) == -1) {
						// not exist then create it 
						if (mkdir(tmp, mode) == -1) {
							fprintf(stderr, "mkdir error: mkdir\n");
							free(tmp);
							return -1;
						}
					}
					*p = '/';
				}
			}
		}
		// above step just ensure the previous directory is created, and then also 
		// have one directory not be created
		if (mkdir(dir_name, mode) == -1) {
			fprintf(stderr, "mkdir error: mkdir\n");
			return -1;
		}
	}

	return 0;
}
